package top.chukongxiang.monitorservice.javafx.core;

import javafx.scene.control.Alert;
import javafx.scene.control.TextArea;
import top.chukongxiang.monitorservice.model.exception.FxException;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author 楚孔响
 * @version 1.0
 * @date 2023/10/26 15:52
 */
public class FxUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    private static Alert alert;

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        e.printStackTrace();
        FxException fxException = FxException.getFxException(e);
        String msg = fxException.getMessage();
        Alert alert = getAlert();
        alert.setHeaderText(msg);
        try (StringWriter stringWriter = new StringWriter()) {
            try (PrintWriter printWriter = new PrintWriter(stringWriter)) {
                e.printStackTrace(printWriter);
                String stackTree = stringWriter.toString();
                TextArea textArea = (TextArea) alert.getDialogPane().getExpandableContent();
                textArea.setText(stackTree);
            }
        } catch (IOException ignore) {
        }
        alert.show();
    }

    public static Alert getAlert() {
        if (alert != null) {
            return alert;
        }
        alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        TextArea textArea = new TextArea();
        textArea.setEditable(false);
        textArea.setWrapText(true);
        alert.getDialogPane().setExpandableContent(textArea);
        return alert;
    }
}
